// pages/payment/payment.js 结算页面
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let wxp = require("../../utils/wxp.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    groupId: '', //如果是参与去拼单的话，需要带这个字段
    ptType: '', //发起拼团和我要参团进来的订单需要
    isFqpt: false, //发起拼团的时候没有groupId
    summitInfo: {
      name: '',
      phone: ''
    },
    orderInfo: null, //订单信息
    skuList: null, //获取数据的skuList
    contentStatus: -1, //1有数据
    isEditable: false,
    item: null, //返回的接口数据
    selectedCoupon: null, //当前选择的优惠券
    actualPayment: 0,
    payNotificationIdList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.获取信息
    this.initData(options);
    //3.获取数据
    this.requestToGetCartConfirm(this.data.skuList);
  },

  //初始化数据
  initData: function (options) {
    let tempUserInfo = user_js.userInfo();
    let tmpSummitInfo = this.data.summitInfo;
    tmpSummitInfo.name = tempUserInfo.userInfo.nickname;
    tmpSummitInfo.phone = tempUserInfo.userInfo.mobile;
    let tmpSkuList = common_js.jsonParse(options.skuList);
    let tmpGroupId = options.groupId ? options.groupId : '';
    let tmpPtType = options.ptType ? options.ptType : '';
    let tmpIsFqpt = options.isFqpt ? options.isFqpt : false;

    this.setData({
      groupId: tmpGroupId,
      ptType: tmpPtType,
      isFqpt: tmpIsFqpt,
      userInfo: tempUserInfo,
      summitInfo: tmpSummitInfo,
      skuList: tmpSkuList
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //确认订单数据
  requestToGetCartConfirm: function (skuList) {
    let requestList = [];
    //1.订阅消息列表
    requestList.push(api.wxRequest(url_js.payNotificationUrl, {}));
    //1.我的自提点
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      shopId: this.data.userInfo.ztd.id,
      skuList: skuList,
      type: this.data.ptType
    }
    requestList.push(api.wxRequest(url_js.cartConfirmUrl, data));
    //获取数据
    Promise.all(requestList).then(results => {
      this.handlePayNotificationData(results[0]);
      this.handelCartConfirmData(results[1]);
    }).catch(err => {
      common_js.log(err);
    });
  },

  // 处理返回的id数组
  handlePayNotificationData(res) {
    this.setData({
      payNotificationIdList: res.result
    });
  },

  //处理返回的数据
  handelCartConfirmData: function (res) {
    let tmpItem = res.result;
    //couponList 
    let tmpCouponList = tmpItem.couponList;
    if (tmpCouponList && tmpCouponList.length > 0) {
      tmpCouponList.forEach(item => {
        let couponItem = item.coupon;
        item.couponFaceValue = couponItem.faceValue + '优惠券';
      });
      tmpItem.couponList = tmpCouponList;
    }

    let tmpSelectCoupon = this.data.selectedCoupon;
    if (tmpItem.couponVo) {
      tmpSelectCoupon = tmpItem.couponVo;
    }

    //计算实际付款
    let tmpMoney = (tmpItem.productAmount - (tmpSelectCoupon ? tmpSelectCoupon.coupon.faceValue : 0)).toFixed(2); // 小于0的时候展示
    if (tmpMoney < 0) {
      tmpMoney = 0.00;
    }

    this.setData({
      contentStatus: 1,
      selectedCoupon: tmpSelectCoupon,
      actualPayment: tmpMoney,
      item: tmpItem
    });
  },

  //创建订单
  requestToOrderCreate: function (userCouponId, skuList) {
    //1.我的自提点
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      mphone: this.data.summitInfo.phone,
      receiver: this.data.summitInfo.name,
      shopId: this.data.userInfo.ztd.id,
      userCouponId: userCouponId,
      skuList: skuList
    }
    api.wxRequest(url_js.orderCreateUrl, data).then(res => {
      //处理订单id等数据
      this.handelOrderCreateData(res);
      //获取微信支付字段 status 1待支付 3已支付 
      if (res.result && res.result.orderId && res.result.status == 1) {
        let prePayData = {
          cityId: this.data.userInfo.ztd.cityId,
          code: user_js.getCode(),
          orderId: res.result.orderId,
          shopId: this.data.userInfo.ztd.id,
        }
        return api.wxRequest(url_js.payPrepareUrl, prePayData);
      }
    }).then(res => {
      //唤醒微信支付
      this.handelPayPrepareData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理订单id等数据
  handelOrderCreateData: function (res) {
    this.setData({
      orderInfo: res.result
    });
    // 已经支付，到订单详情页面
    if (res.result.status == 3) {
      wx.redirectTo({
        url: '../myOrderDetail/myOrderDetail?orderId=' + this.data.orderInfo.orderId
      });
    }
  },

  //创建团购订单
  requestToOrderCreateGroup: function (userCouponId, skuList) {
    //1.我的自提点
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      groupId: this.data.groupId,
      mphone: this.data.summitInfo.phone,
      receiver: this.data.summitInfo.name,
      shopId: this.data.userInfo.ztd.id,
      userCouponId: userCouponId,
      skuList: skuList
    }
    api.wxRequest(url_js.orderCreateGroupUrl, data).then(res => {
      //处理订单id等数据
      this.handelOrderCreateGroupData(res);
      //获取微信支付字段 status 1待支付 3已支付 
      if (res.result && res.result.orderId) {
        let prePayData = {
          cityId: this.data.userInfo.ztd.cityId,
          code: user_js.getCode(),
          orderId: res.result.orderId,
          shopId: this.data.userInfo.ztd.id,
        }
        return api.wxRequest(url_js.payPrepareUrl, prePayData);
      }
    }).then(res => {
      //唤醒微信支付
      this.handelPayPrepareData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理订单id等数据
  handelOrderCreateGroupData: function (res) {
    this.setData({
      orderInfo: res.result
    });
  },

  //处理返回的预付款
  handelPayPrepareData: function (res) {
    let payItem = res.result;
    //优惠券不能使用，因为有限时折扣商品
    if (res.code == 999) {
      common_js.showModal("订单中存在限时折扣商品，无法使用优惠券，是否继续支付？", null, true, "取消订单", "继续支付", () => {
        //确定
        this.payOrderByWechat(payItem);
      }, () => {
        //取消
        this.requestToOrderCancel(this.data.orderInfo.orderId);
      })
      return;
    }
    //直接支付
    this.payOrderByWechat(payItem);
  },

  //取消订单
  requestToOrderCancel: function (orderId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderCancelUrl, data).then(res => {
      this.handleOrderCancelData(res, orderId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理取消订单的数据
  handleOrderCancelData: function (res, orderId) {
    common_js.showToast("订单已取消");
    //跳转到订单详情页
    wx.redirectTo({
      url: '../myOrderDetail/myOrderDetail?orderId=' + this.data.orderInfo.orderId
    });
  },

  //微信支付订单
  payOrderByWechat: function (payItem) {
    //微信支付
    wx.requestPayment({
      timeStamp: payItem.timeStamp,
      nonceStr: payItem.nonceStr,
      package: payItem.package,
      signType: payItem.signType,
      paySign: payItem.paySign,
      success: res => {
        //根据订单id跳转到待取货订单详情
        //是否是团购
        if (payItem.groupId) {
          wx.redirectTo({
            url: '../myPintuaDetail/myPintuaDetail?groupId=' + payItem.groupId
          });
        } else {
          wx.redirectTo({
            url: '../myOrderDetail/myOrderDetail?orderId=' + this.data.orderInfo.orderId
          });
        }
      },
      fail: res => {
        if (common_js.containsKeyString(res.errMsg, "fail cancel")) {
          //根据订单id跳转到代待款订单详情
          wx.redirectTo({
            url: '../myOrderDetail/myOrderDetail?orderId=' + this.data.orderInfo.orderId
          });
        } else {
          common_js.showToast(res.errMsg);
        }
      }
    })
  },

  //编辑收货信息
  onEditShxx: function (e) {
    this.setData({
      isEditable: true
    });
  },

  //保存收货信息
  onSaveShxx: function () {
    if (!common_js.isPhone(this.data.summitInfo.phone)) {
      common_js.showToast('请输入正确的手机号!');
      return;
    }
    this.setData({
      isEditable: false
    });
  },

  //输入姓名
  bindInputName: function (e) {
    let value = e.detail.value;
    let tmpSummitInfo = this.data.summitInfo;
    tmpSummitInfo.name = value;
    this.setData({
      summitInfo: tmpSummitInfo
    });
  },

  //输入电话
  bindInputPhone: function (e) {
    let value = e.detail.value;
    let tmpSummitInfo = this.data.summitInfo;
    tmpSummitInfo.phone = value;
    this.setData({
      summitInfo: tmpSummitInfo
    });
  },

  //联系连长
  contactDz: function () {
    if (!this.data.userInfo.ztd.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.userInfo.ztd.mobile
    })
  },

  //改变优惠券
  onCoupndeChange: function (e) {
    //index
    let index = parseInt(e.detail.detail.value);
    let tmpItem = this.data.item;
    let couponItem = tmpItem.couponList[index];
    tmpItem.couponVo = couponItem;

    //计算实际付款
    let tmpMoney = (this.data.item.productAmount - couponItem.coupon.faceValue).toFixed(2);
    // 小于0的时候展示
    if (tmpMoney < 0) {
      tmpMoney = 0.00;
    }

    this.setData({
      selectedCoupon: couponItem,
      actualPayment: tmpMoney,
      item: tmpItem
    })
  },

  // 获取通知的id
  getSubscribeMessagetmplIds() {
    return this.data.payNotificationIdList.map(item => {
      return item.id;
    });
  },

  // 检查模板消息发送情况
  subscribeMessageSuccessStatusList(res) {
    return this.data.payNotificationIdList.filter(item => {
      return res[item.id] == 'accept';
    });
  },

  // 订阅消息弹框
  subscribeMessage() {
    let ids = this.getSubscribeMessagetmplIds();
    wxp.requestSubscribeMessage({
      tmplIds: ids
    }).then(res => {
      let list = this.subscribeMessageSuccessStatusList(res);
      if (list.length != 0 && (list.length != this.data.payNotificationIdList.length)) {
        this.goSettingUI('亲，我们未获得您的全部订阅消息推送权限，是否打开设置?');
      } else {
        // 去结算
        this.gotoPay();
      }
    }).catch(err => {
      if (err.errCode == 20004) {
        //打开设置
        this.goSettingUI('亲，我们未获得您的订阅消息推送权限，是否打开设置?');
      } else {
        // 去结算
        this.gotoPay();
      }
    });
  },

  // 提示是否打开消息推送设置页面
  goSettingUI(content) {
    wxp.showModal({
      content: content
    }).then(res => {
      // 打开设置
      return wxp.openSetting({
        withSubscriptions: true
      });
    }).then(res => {
      // 打开设置，并返回
      common_js.log(res);
    }).catch(err => {
      common_js.log(err);
      this.gotoPay();
    });
  },

  //去结算
  gotoPay: function () {
    if (this.data.summitInfo.name == 0) {
      common_js.showToast("请填写收货人姓名");
      return
    }
    if (this.data.summitInfo.phone == 0) {
      common_js.showToast("请填写收货人电话");
      return
    }
    if (!common_js.isPhone(this.data.summitInfo.phone)) {
      common_js.showToast('请输入正确的手机号!');
      return;
    }

    //判断商品剩余库存
    let checkObj = this.getAbNormalGoods(this.data.item.userCartVoList);
    if (checkObj) {
      let checkItem = this.data.item.userCartVoList[checkObj.index];
      //提示打开设置
      common_js.showModal(checkItem.title + checkItem.checkMessage, null, true, "放弃", "去购物车", () => {
        wx.navigateBack({});
      })
      return;
    }
    //支付结算
    let couponId = this.data.selectedCoupon ? this.data.selectedCoupon.id : '';
    //是否是团购
    if (this.data.groupId || this.data.isFqpt) {
      this.requestToOrderCreateGroup(couponId, this.data.item.userCartVoList);
    } else {
      this.requestToOrderCreate(couponId, this.data.item.userCartVoList);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.paymentPay);
  },

  //获取不能正常购买的商品,如果有返回index
  getAbNormalGoods: function (goodsList) {
    let obj = {};
    for (let i = 0; i < goodsList.length; i++) {
      let item = goodsList[i];
      if (!item.checkFlag) {
        obj.index = i;
        return obj;
      }
    }
    return null;
  },
})